#include <apue.h>
#include <stdio.h>
#include <sys/wait.h>
#include <string.h>

const int MAX_BUFF_SIZE = 4096;

int main() {
    char buf[MAX_BUFF_SIZE];
    pid_t pid;
    int status, len;

    printf("%% ");

    while (fgets(buf, MAX_BUFF_SIZE, stdin) != 0) {
        len = strlen(buf);
        // 如果长度为1，说明是空行，只包含一个\n选项
        if (len == 1)
            continue;
        if (buf[len - 1] == '\n') {
            buf[len - 1] = 0;
        }
        if ((pid = fork()) < 0) {
            err_sys("fork error");
        } else if (pid == 0) {
            execlp(buf, buf, (char *)0);
            err_ret("couldn't execute: %s", buf);
            exit(127);
        }

        if ((pid = waitpid(pid, &status, 0)) < 0) {
            err_sys("waitpid error");
        }
        printf("%% ");
    }

    return 0;
}
